<template>
	<div>
		<!-- 编辑弹框 -->
		<el-dialog :model-value="dialogVisible" :show-close="false" :before-close="handleClose" width="35%">
			<template #header="{ titleId, titleClass }">
				<div class="my-header">
					<h4 :id="titleId" :class="titleClass">{{ headerTitle }}</h4>
					<el-button type="danger" plain size="small" class="custom-close-btn" @click="handleSilentClose">
						<el-icon :size="16"><Close /></el-icon>
					</el-button>
				</div>
			</template>
			<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="ruleForm" :size="formSize" status-icon>
				<el-form-item label="用户" prop="uid">
					<el-select v-model="form.uid" filterable clearable>
						<el-option v-for="(item, index) in userList" :key="index.toString()" :label="item.username" :value="item.id"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="所属视频" prop="vid">
					<el-select v-model="form.vid" filterable clearable>
						<el-option v-for="(item, index) in videoList" :key="index.toString()" :label="item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="弹幕内容" prop="content">
					<el-input v-model="form.content" type="textarea" :rows="3" maxlength="50" show-word-limit />
				</el-form-item>

				<el-form-item label="弹幕颜色" prop="color">
					<el-color-picker v-model="form.color" show-alpha :predefine="predefineColors" />
				</el-form-item>

				<el-form-item label="弹幕类型" prop="type">
					<el-select v-model="form.type">
						<el-option label="滚动弹幕" :value="0" />
						<el-option label="顶部固定" :value="1" />
					</el-select>
				</el-form-item>

				<el-form-item label="出现时间(秒)" prop="time">
					<el-input-number v-model="form.time" :min="0" :step="0.1" :precision="2" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleResetForm(ruleFormRef)">取消</el-button>
					<el-button type="primary" @click="handleSubmitForm(ruleFormRef)">提交</el-button>
				</span>
			</template>
		</el-dialog>

		<el-row>
			<!-- 分页查询表单按钮 -->
			<el-col>
				<el-form :inline="true">
					<el-row>
						<el-col>
							<el-form-item label-width="5px" style="width: 200px">
								<el-input v-model="content" placeholder="弹幕内容" clearable @change="load" />
							</el-form-item>

							<el-form-item label-width="5px" style="width: 200px">
								<el-select v-model="uid" placeholder="选择用户" filterable clearable @change="load">
									<el-option v-for="(item, index) in userList" :key="index.toString()" :label="item.username" :value="item.id"></el-option>
								</el-select>
							</el-form-item>

							<el-form-item label-width="5px" style="width: 200px">
								<el-select v-model="vid" placeholder="选择视频" filterable clearable @change="load">
									<el-option v-for="(item, index) in videoList" :key="index.toString()" :label="item.name" :value="item.id"></el-option>
								</el-select>
							</el-form-item>

							<el-form-item label-width="5px">
								<el-button type="primary" :icon="Search" @click="load">查询</el-button>
								<el-button type="warning" :icon="Refresh" @click="handleReset">重置</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-col>
			<!-- 新增和批量按钮 -->
			<el-col style="margin-bottom: 10px; display: flex; gap: 10px">
				<div v-permission="'sys:barrage:batch:delete'">
					<el-popconfirm
						confirm-button-text="确定"
						cancel-button-text="取消"
						:icon="InfoFilled"
						icon-color="#626AEF"
						title="确认要批量删除吗？"
						@confirm="handleBatchDel"
						@cancel="load"
					>
						<template #reference>
							<el-button type="danger" :disabled="disabled" :icon="Delete" size="small" plain>批量删除</el-button>
						</template>
					</el-popconfirm>
				</div>
			</el-col>
			<!-- 表格页面 -->
			<el-col>
				<el-table
					:data="tableData"
					style="width: 100%"
					:header-cell-style="{ background: '#eef1f6', color: '#606266' }"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" />
					<el-table-column prop="id" label="ID" align="center" sortable />
					<el-table-column prop="content" label="内容" align="center" width="200">
						<template #default="scope">
							<span>{{ scope.row.content }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="color" label="颜色" align="center">
						<template #default="scope">
							<div
								:style="{
									backgroundColor: scope.row.color,
									border: '1px solid black',
									width: '24px',
									height: '24px',
									margin: '0 auto',
									borderRadius: '3px'
								}"
							></div>
						</template>
					</el-table-column>
					<el-table-column prop="time" label="出现时间" align="center" />
					<el-table-column prop="user.username" label="用户" align="center" />
					<el-table-column prop="video.name" label="视频" align="center" />
					<el-table-column prop="createTime" label="创建时间" align="center" />

					<el-table-column label="操作" align="center">
						<template #default="scope">
							<div style="display: flex; justify-content: center; gap: 10px">
								<div>
									<el-button v-permission="'sys:barrage:update'" type="primary" :icon="Edit" size="small" @click="handleUpdate(scope.row.id)">
										编辑
									</el-button>
								</div>
								<div v-permission="'sys:barrage:delete'">
									<el-popconfirm
										confirm-button-text="确定"
										cancel-button-text="取消"
										:icon="InfoFilled"
										icon-color="#626AEF"
										title="确认要删除吗？"
										@confirm="handleDel(scope.row.id)"
										@cancel="load"
									>
										<template #reference>
											<el-button type="danger" :icon="Delete" size="small">删除</el-button>
										</template>
									</el-popconfirm>
								</div>
							</div>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页按钮 -->
				<div class="pagination">
					<el-pagination
						:current-page="pageNum"
						:page-size="pageSize"
						:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
						size="small"
						layout="total, sizes, prev, pager, next, jumper"
						:total="Number(total)"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { CircleCloseFilled, Close, Delete, Download, Edit, InfoFilled, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'

const predefineColors = ref(['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585', '#ffffff', '#000000'])

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const userList = ref([])
const videoList = ref([])
const content = ref('')
const uid = ref('')
const vid = ref('')

const form = reactive({
	id: undefined,
	uid: undefined,
	vid: undefined,
	content: '',
	color: '#ffffff',
	type: 0,
	time: 0,
	createTime: undefined
})

const formSize = ref('default')
const ruleFormRef = ref()

const rules = reactive({
	uid: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	vid: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	color: [{ required: true, message: '请选择颜色', trigger: 'change' }],
	type: [{ required: true, message: '请选择类型', trigger: 'change' }],
	time: [{ required: true, message: '请输入时间', trigger: 'blur' }]
})

// 初始化加载
const load = async () => {
	const [usersRes, videosRes] = await Promise.all([request.get('/user'), request.get('/video')])
	userList.value = usersRes.data
	videoList.value = videosRes.data

	const res = await request.get('/barrage/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			content: content.value,
			uid: uid.value,
			vid: vid.value
		}
	})

	tableData.value = res.data.records.map(item => ({
		...item,
		user: userList.value.find(u => u.id === item.uid),
		video: videoList.value.find(v => v.id === item.vid)
	}))

	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
}

load()

const handleAdd = () => {
	headerTitle.value = '新增弹幕'
	dialogVisible.value = true
}

const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = '编辑弹幕'
	const res = await request.get(`/barrage/${id}`)
	Object.assign(form, res.data)
}

const handleDel = async id => {
	await request.delete(`/barrage/${id}`)
	ElMessage.success('删除成功')
	await load()
}

const handleBatchDel = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	await request.delete(`/barrage/batch/${ids}`)
	ElMessage.success('批量删除成功')
	await load()
}

const handleReset = () => {
	content.value = ''
	uid.value = ''
	vid.value = ''
	load()
}

const handleSizeChange = size => {
	pageSize.value = size
	load()
}

const handleCurrentChange = current => {
	pageNum.value = current
	load()
}

const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

const handleSilentClose = () => {
	handleResetForm(ruleFormRef.value)
	dialogVisible.value = false
}

const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
}

const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}
	await formEl.validate(async valid => {
		if (valid) {
			const method = form.id ? 'put' : 'post'
			const url = form.id ? `/barrage/${form.id}` : '/barrage'
			await request({ method, url, data: form })
			ElMessage.success('操作成功')
			await handleResetForm(formEl)
		}
	})
}

const beforeBatchUpload = async file => {
	const fd = new FormData()
	fd.append('file', file)
	await request.post('/barrage/batch/upload', fd, {
		headers: { 'Content-Type': 'multipart/form-data' }
	})
	ElMessage.success('上传成功')
	await load()
}

const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request.get(`/barrage/batch/export/${ids}`, { responseType: 'blob' })
	downloadExcel(res, '弹幕数据')
}

const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()
	Object.assign(form, {
		id: undefined,
		uid: undefined,
		vid: undefined,
		content: '',
		color: '#ffffff',
		type: 0,
		time: 0,
		createTime: undefined
	})
	dialogVisible.value = false
	await load()
}
</script>

<style scoped>
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.pagination {
	margin-top: 10px;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}

.custom-close-btn {
	border: none !important;
	padding: 5px !important;
	transition: all 0.3s;
}

.custom-close-btn:hover {
	transform: rotate(90deg);
	color: #ff4d4f !important;
	background: rgba(255, 77, 79, 0.1) !important;
}
</style>
